<template>
  <el-form
    ref="formRef"
    :model="formItemData"
    :rules="formRules"
    v-loading="formLoading"
    :inline-message="true"
    :disabled="disabled"
  >

    <el-form label-position="right">

      <el-row :gutter="10">
        <!--          <el-col :span="5">-->
        <!--&lt;!&ndash;            <div class="text-gray-500"&ndash;&gt;-->
        <!--&lt;!&ndash;                 style="text-align: center;color: #999;font-weight: 800;margin-top: 5px">筛选:&ndash;&gt;-->
        <!--&lt;!&ndash;            </div>&ndash;&gt;-->
        <!--          </el-col>-->
        <el-col :span="7">
          <el-input placeholder="请输入VIN" @change="onChangeProductInfoQuery"
                    v-model="productQuery.vin" clearable/>
        </el-col>
        <el-col :span="4">
          <el-input placeholder="产品名称" @change="onChangeProductInfoQuery"
                    v-model="productQuery.name" clearable/>
        </el-col>
        <el-col :span="13" class="mt-1">
          <label class="text-gray-8">车型:{{ carTypeName }}</label>
        </el-col>
      </el-row>
      <el-row :gutter="3" class="mt-2">
        <el-col :span="6">
          <el-form-item label="" prop="categoryId">
            <el-tree-select
              v-model="productQuery.categoryId"
              :data="categoryList"
              :props="defaultProps"
              check-strictly
              clearable
              @change="onChangeProductInfoQuery"
              default-expand-all
              placeholder="业务"
            />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="" prop="brandId">
            <el-tree-select
              v-model="productQuery.brandId"
              :data="brandList"
              @change="onChangeProductInfoQuery"
              :filterable="true"
              :props="defaultProps"
              clearable
              check-strictly
              default-expand-all
              placeholder="品牌"
            />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="" prop="businessType">
            <el-select v-model="productQuery.businessType"
                       :filterable="true"
                       @change="onChangeProductInfoQuery"
                       placeholder="部位" clearable>
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_SALE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button @click="onResetProductQuery">重置</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openAddProduct" round>+新增产品信息</el-button>
        </el-col>
      </el-row>

    </el-form>

    <el-table :data="formItemData" border
              class="-mt-10px">
      <el-table-column label="产品名称" align="center">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
            >
              <el-option
                v-for="item in  row.productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="订单价" align="center" width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.;`" class="mb-0px!">
            <!--            <el-input-number-->
            <!--              v-model="row.orderPrice"-->
            <!--              controls-position="right"-->
            <!--              :min="0"-->
            <!--              :precision="0"-->
            <!--              class="!w-100%"-->
            <!--            />-->
            <el-input
              v-model="row.orderPrice"
            />
          </el-form-item>
        </template>
      </el-table-column>

<!--      <el-table-column label="派单价" align="center" width="120">-->
<!--        <template #default="{ row, $index }">-->
<!--          <el-form-item :prop="`${$index}.;`" class="mb-0px!">-->
<!--            <el-input-->
<!--              v-model="row.dispatchPrice"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <!--      <el-table-column align="center" fixed="right" label="操作" width="60">-->
      <!--        <template #default="{ $index }">-->
      <!--          <el-button @click="handleDelete($index)" link>—</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <el-divider content-position="left">参考价格</el-divider>
    <el-tag class="mr-3" v-for="(value, key, index) in mapPrice" :key="index">【{{key}}】{{value}}</el-tag>
    <el-table v-loading="historyPriceLoading" :data="historyPriceList" border :stripe="true"
              :show-overflow-tooltip="true">
      <el-table-column label="客户名称" align="center" prop="custName"/>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="订单时间" align="center" prop="orderTime"
                       :formatter="dateFormatter2"/>
      <el-table-column label="价格" align="center" prop="orderPrice"/>
    </el-table>

  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <!--    <el-button @click="handleItemAdd" round>+ 添加采购产品</el-button>-->
    <!--    <el-button type="primary" @click="openAddProduct" round>+ 新增产品信息</el-button>-->
    <!--    <el-button type="primary" @click="handlePurchase" round>提交采购入库</el-button>-->
  </el-row>
</template>
<script setup lang="ts">
import {FinancePaymentApi, FinancePaymentVO} from '@/api/erp/finance/payment'
import {PurchaseOrderApi, PurchaseOrderVO} from '@/api/erp/purchase/order'
import {PurchaseInApi, PurchaseInVO} from '@/api/erp/purchase/in'
import {ProductApi, ProductVO} from '@/api/erp/product/product'
import {StockApi} from '@/api/erp/stock/stock'
import {SupplierApi, SupplierVO} from '@/api/erp/purchase/supplier'
import {ElMessage, ElLoading} from 'element-plus'
import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from '@/utils/dict'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'
import {ErpBizType} from "@/utils/constants";
import {ProductCategoryApi, ProductCategoryVO} from "@/api/erp/product/category";

const categoryList = ref<ProductCategoryVO[]>([]) // 产品分类列表
const brandList = ref<ProductBrandVO[]>([]) // 产品分类列表
const {push} = useRouter()
import {defaultProps, handleTree} from '@/utils/tree'
import {ProductBrandApi, ProductBrandVO} from "@/api/erp/product/brand";
import {InquiryOrderApi} from "@/api/erp/inquiryorder";
import {dateFormatter, dateFormatter2} from '@/utils/formatTime'
const props = defineProps<{
  items: undefined
  disabled: false,
  productId: undefined,
  amSeriesName: undefined,
  oe: undefined,
  brandId: undefined,
  factoryNumber: undefined
}>()
const formLoading = ref(false) // 表单的加载中

const carTypeName = ref() // 车型
const formItemData = ref([])
const formRules = reactive({
  productId: [{required: true, message: '产品不能为空', trigger: 'blur'}],
  count: [{required: true, message: '产品数量不能为空', trigger: 'blur'}]
})


//历史价格相关
const historyPriceLoading = ref(false) // 表单的加载中
const mapPrice = ref();
const historyPriceList = ref([])

/**
 * 产品搜索条件
 */
const productQuery = reactive({
  categoryId: undefined,
  name: undefined,
  vin: undefined,
  businessType: undefined,//部位
  brandId: undefined
})


function openAddProduct() {
  push({
    path: "/erp/product/product",
    query: {doType: "quickAdd", data: JSON.stringify(productQuery)}
  });
  // push({path: "/erp/product/product", query: {doType: "handAdd"}});
}


const formRef = ref([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
const supplierList = ref<SupplierVO[]>([]) // 供应商列表
/** 初始化设置出库项 */
watch(
  () => props.items,
  async (val) => {
    formItemData.value = val
  },
  {immediate: true}
)



//查看价格详情
const openHistoryPriceDetail = async (productId: number) => {
  historyPriceLoading.value = true;
  historyPriceList.value = [];
  let r = await InquiryOrderApi.historyPriceDetail(productId)
  historyPriceList.value = r.list;
  mapPrice.value = r.mapPrice;
  historyPriceLoading.value = false;
}

//监听productList
watch(
  () => productList.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    formItemData.value.forEach(item => {
      //item产品列表
      item.productList = [];
      let concatList = item.productList.concat(productList.value);
      item.productList = concatList;
    })

  }
)

/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formItemData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {

      //初始化采购属性
      if (item.supplierId == undefined) {
        item.supplierId = undefined;
      }
      if (item.purchasePrice == undefined) {
        item.purchasePrice = undefined;
      }
      //end


      item.totalProductPrice = erpPriceMultiply(item.productPrice, item.count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, item.taxPercent / 100.0)
      // item.allPurchasePrice += item.purchasePrice*item.count;
      if (item.totalProductPrice != null) {
        item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
      } else {
        item.totalPrice = undefined
      }
    })
  },
  {deep: true}
)


/** 新增按钮操作 */
function handleItemAdd() {

  const itemRow = {
    id: undefined,
    productId: undefined,
    count: 1,
    productList: []
  }

  // if (formItemData.value[0] != undefined && formItemData.value[0].productList != undefined && formItemData.value[0].productList.length > 0) {
  //   itemRow.productList = formItemData.value[0].productList;
  // }
  formItemData.value.push(itemRow)


}

/** 删除按钮操作 */
const handleDelete = (index: number) => {
  formItemData.value.splice(index, 1)
}


const preProductIdBindOE = ref(undefined)
const syncOE = ref(String)
/** 处理产品变更 */
const onChangeProduct = (productId, row) => {

  openHistoryPriceDetail(productId);

  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productUnitName = product.unitName
    row.productBarCode = product.barCode
    row.productPrice = product.salePrice
  }
  // 加载库存
  setStockCount(row)

  if (product == undefined) {
    return;
  }
  if (product.oe != undefined && product.oe != null && product.oe.length > 0) {
    return;
  }
  if (syncOE.value == undefined || syncOE.value.length == 0) {
    return;
  }
  // 之前的绑定的
  let preProductId = preProductIdBindOE.value;
  //同步记录历史绑定oe
  preProductIdBindOE.value = productId;

  ProductApi.bindOE({
    preBindOEProductId: preProductId,
    bindOEProductId: productId,
    oe: syncOE.value
  });

  //获取row里面所有的productId 集合
  // const productIds = formItemData.value.map((item) => item.productId);
  // //剔出最后一个
  // productIds.pop();
  // //productId是否在productIds集合中
  // if (productIds.length > 0 && productIds.includes(productId)) {
  //   // formItemData.value.splice(index, 1)
  //   row.productId = undefined;
  //   ElMessage.error("产品不能重复");
  //   return;
  // }


}


/** 重置查询产品列表 */
const onResetProductQuery = () => {
  productQuery.categoryId = undefined;
  productQuery.name = undefined;
  productQuery.brandId = undefined;
  productQuery.vin = undefined;
  productQuery.businessType = undefined;
  productList.value = [];
}

//产品名称查询
const onChangeProductInfoQuery = async () => {

  await handleProductList();
  formItemData.value.forEach(item => {
    //item产品列表
    item.productList = [];
    let concatList = item.productList.concat(productList.value);
    item.productList = concatList;
  })
}


/** 加载库存 */
const setStockCount = async (row: any) => {
  if (!row.productId) {
    return
  }
  // const count = await StockApi.getStockCount(row.productId)
  // row.stockCount = count || 0
}

const purchaseOrder = ref<PurchaseOrderVO>()
const purchaseOrderItem = ref<[]>();

// const getItemProdcutList = async (row) => {
//   console.log(row.productList)
//   const data = row.productList != undefined ? row.productList : productList.value;
//   console.log(data, '===============');
//   return data
// }

//提交采购
const handlePurchase = async () => {

  //校验是否存在产品信息
  formItemData.value.forEach(item => {
    if (item.productId == undefined) {
      ElMessage.error("请先选择产品");
      return;
    }
  })

  //产品库存为0 的商品列表
  // let purchaseListZero = formItemData.value.filter(item => item.stockCount == 0);
  let purchaseListZero = formItemData.value.filter(item => item.count - item.stockCount > 0);

  if (purchaseListZero.length == 0) {
    ElMessage.error("暂无需采购产品");
    return;
  }

  //校验列表库存为0的采购商是否选择
  for (let i = 0; i < purchaseListZero.length; i++) {
    if (purchaseListZero[i].productId == undefined) {
      ElMessage.error("请选择产品！");
      return;
    }
    if (purchaseListZero[i].supplierId == undefined) {
      ElMessage.error("请选择采购商！");
      return;
    }
    if (purchaseListZero[i].purchasePrice == undefined) {
      ElMessage.error("请填写采购价！");
      return;
    }
  }

  //获取供应商id
  let supplierIdList = purchaseListZero.map(item => item.supplierId)
  supplierIdList = new Set(supplierIdList);

  //创建各采购商的采购订单
  supplierIdList.forEach(async (supplierId) => {

    //对应供应商的产品信息
    let productList = [];
    purchaseListZero.forEach(async (item) => {
      if (item.supplierId === supplierId) {
        let needCount = item.count - item.stockCount;
        productList.push({
          productId: item.productId,
          name: undefined, // 产品名称
          barCode: undefined, // 产品条码
          categoryId: undefined, // 产品类型编号
          unitId: undefined, // 单位编号
          unitName: undefined, // 单位名字
          status: undefined, // 产品状态
          standard: undefined, // 产品规格
          remark: undefined, // 产品备注
          expiryDay: undefined, // 保质期天数
          weight: undefined, // 重量（kg）
          productPrice: item.purchasePrice, // 采购价格，单位：元
          salePrice: undefined, // 销售价格，单位：元
          minPrice: undefined, // 最低价格，单位：元
          count: needCount
        });
      }
    })
    //采购项
    let orderItem = {
      supplierId: supplierId,
      accountId: undefined,
      orderTime: Date.now(),
      remark: undefined,
      fileUrl: undefined,
      discountPercent: 0,
      discountPrice: 0,
      totalPrice: 0,
      depositPrice: 0,
      items: productList
    }


    const loading = ElLoading.service({
      lock: true,
      text: '采购入库中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    try {
      /**
       * 1.1生成采购单
       */
      let purchaseId = await PurchaseOrderApi.createPurchaseOrder(orderItem);
      /**
       * 1.2 审批成功单
       */
      await PurchaseOrderApi.updatePurchaseOrderStatus(purchaseId, 20);


      /**
       * 2.1 查询采购单
       */
      purchaseOrder.value = await PurchaseOrderApi.getPurchaseOrder(purchaseId);
      let purchaseOrderNo = purchaseOrder.value.no;
      let supplierId = purchaseOrder.value.supplierId;
      //采购入库信息
      let purchaseInForm = {
        supplierId: supplierId,
        orderNo: purchaseOrderNo,
        orderId: purchaseId,
        accountId: 4,
        inTime: Date.now(),
        remark: undefined,
        fileUrl: undefined,
        discountPercent: 0,
        discountPrice: 0,
        totalPrice: 0,
        otherPrice: 0,
        items: []
      }
      /**
       *2.2采购入库订单项封装
       */
      purchaseOrderItem.value = purchaseOrder.value.items;
      for (let i = 0; i < purchaseOrderItem.value.length; i++) {
        purchaseOrderItem.value[i].warehouseId = 3;
        purchaseOrderItem.value[i].orderItemId = purchaseOrderItem.value[i].id;
        purchaseOrderItem.value[i].id = undefined;
      }
      purchaseInForm.items = purchaseOrderItem.value;
      /**
       * 2.3创建采购入库
       */
      let purchaseInId = await PurchaseInApi.createPurchaseIn(purchaseInForm);
      /**
       * 2.4审核成功入库 (调整为入库审核生成付款单)
       */
      // await PurchaseInApi.updatePurchaseInStatus(purchaseInId, 20);


      /**
       * 3.1查询采购入库单
       */
      // let purchaseInInfo = await PurchaseInApi.getPurchaseIn(purchaseInId);

      /**
       * 3.2封装付款单
       */
      // const paymentFormData = {
      //   supplierId: purchaseInInfo.supplierId,
      //   accountId: purchaseInInfo.accountId,
      //   financeUserId: undefined,
      //   paymentTime: undefined,
      //   remark: undefined,
      //   fileUrl: '',
      //   totalPrice: purchaseInInfo.totalProductPrice,
      //   discountPrice: 0,
      //   paymentPrice: purchaseInInfo.totalProductPrice,
      //   items: [],
      //   no: undefined // 订单单号，后端返回
      // }
      // paymentFormData.items.push({
      //   bizId: purchaseInInfo.id,
      //   bizType: ErpBizType.PURCHASE_IN,
      //   bizNo: purchaseInInfo.no,
      //   totalPrice: purchaseInInfo.totalProductPrice,
      //   paidPrice: 0,
      //   paymentPrice: purchaseInInfo.totalProductPrice
      // })

      /**
       * 3.3创建付款单
       */
      // await FinancePaymentApi.createFinancePayment(paymentFormData)


      ElMessage({
        message: '采购入库成功',
        type: 'success',
      })


      /**
       * 4.1更新库存
       */
      for (let i = 0; i < formItemData.value.length; i++) {
        const row = formItemData.value[i]
        const count = await StockApi.getStockCount(row.productId);

        formItemData.value[i].stockCount = count;
      }


    } finally {
      setTimeout(() => {
        loading.close()
      }, 500)
    }

  })

}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
defineExpose({validate, productList, carTypeName})


/**
 * 获取产品信息
 */
const handleProductList = async () => {

  if (productQuery.vin != undefined && productQuery.vin.length > 0) {

    //vin 剔除多余的空格
    productQuery.vin = productQuery.vin.replace(/\s+/g, '');

    if (productQuery.vin.length != 17) {
      ElMessage.error('请输入正确的17位VIN');
    }
    //自动玻璃
    productQuery.categoryId = 87;

    //默认部位
    if (productQuery.businessType == undefined) {
      productQuery.businessType = 1;
    }
    //默认品牌
    if (productQuery.brandId == undefined) {
      productQuery.brandId = 1;
    }
  }


  let queryParams = {
    name: productQuery.name,
    brandId: productQuery.brandId,
    businessType: productQuery.businessType,
    categoryId: productQuery.categoryId,
    vin: productQuery.vin
  }

  //提示查询中
  ElLoading.service({
    lock: true,
    text: '查询中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  let rData = null;
  try {
    rData = await ProductApi.queryOrAdd(queryParams);
  } finally {
    //关闭loading
    setTimeout(() => {
      ElLoading.service().close()
    }, 500)
  }

  //未查询到对应车型，提示添加产品信息
  if (rData.length == 1 && rData[0].newData) {
    //是否新增产品信息
    ElMessageBox.confirm('未查询到对应产品信息，是否新增产品信息？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      let productData = rData[0];
      // productData.name = productData.amBrandName + productData.amSeriesName + productData.amVehicleName;
      //添加产品信息
      productData.vin = productQuery.vin;

      ElLoading.service({
        lock: true,
        text: '处理中...',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      await ProductApi.createProduct(productData);

      //关闭loading
      setTimeout(() => {
        ElLoading.service().close()
      }, 500)

      // const productVo = await ProductApi.getProduct(productId);
      // //productVo 转list
      // await productList.value.push(productVo);
      rData = await ProductApi.queryOrAdd(queryParams)
      syncProductList(rData);
      //提示添加成功
      ElMessage({
        message: '新增产品信息成功',
        type: 'success',
      });

    }).catch((e) => {

      productQuery.name = rData[0].amSeriesName;
      onChangeProductInfoQuery();

      ElMessage({
        type: 'info',
        message: '已取消新增'
      });
    }).finally(() => {
      syncOE.value = rData[0].oe;
      // productQuery.name = rData[0].amSeriesName;

      carTypeName.value = rData[0].amBrandName + rData[0].amSeriesName + rData[0].amVehicleName;
    });
    return;
  } else {
    syncProductList(rData);
  }

}

const syncProductList = async (rData) => {
  productList.value = [];
  const dataList = rData;
  for (const key in dataList) {
    let getName = '';
    if (dataList[key].brandName != undefined && dataList[key].brandName.length > 0) {
      getName = "【" + dataList[key].brandName + "】";
      getName = getName + dataList[key].name;
    }
    if (dataList[key].businessTypeName != undefined && dataList[key].businessTypeName.length > 0) {
      getName = getName + dataList[key].businessTypeName;
    }
    dataList[key].name = getName;
  }
  productList.value = dataList;
  console.log(productList.value)
}

/** 初始化 */
onMounted(async () => {
  preProductIdBindOE.value = undefined;
  syncOE.value = undefined;
  // 产品分类
  const categoryData = await ProductCategoryApi.getProductCategorySimpleList()
  categoryList.value = handleTree(categoryData, 'id', 'parentId')

  // 加载品牌列表
  const brandData = await ProductBrandApi.getProductBrandSimpleList()
  brandList.value = handleTree(brandData, 'id', 'parentId')

  // 加载供应商列表
  // supplierList.value = await SupplierApi.getSupplierSimpleList();

  // 默认添加一个
  if (formItemData.value.length === 0) {
    handleItemAdd()
  }
})
</script>
